<template>
  <div class="form-wrapper">
    <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
      <el-form-item prop="phone">
        <el-input v-model="loginForm.phone" placeholder="请输入手机号">
          <template #prefix>
            <el-icon class="el-input__icon"><user /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <div class="captcha-frame-wrapper">
        <div class="captcha-frame">
          <el-form-item prop="code">
            <el-input placeholder="短信验证码" v-model="loginForm.code" @keyup.enter="login">
              <template #prefix>
                <el-icon class="el-input__icon"><Key /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </div>
        <div class="captcha-box">
          <el-button style="width: 100%" type="primary" :loading-icon="Eleme" :loading="!canClick" @click="handleSendCode">{{
            buttonCtn
          }}</el-button>
        </div>
      </div>
    </el-form>
    <div class="login-btn">
      <el-button :icon="UserFilled" @click="login(loginFormRef)" size="large" type="primary" :loading="loading"> 登录 </el-button>
    </div>
    <div class="info-wrapper">
      <el-checkbox v-model="checked2"> </el-checkbox>
      <span class="note note-ml10">我已阅读并同意千万职联 </span>
      <el-button type="primary" link class="info-btn">用户协议</el-button> <span class="note">和</span>
      <el-button type="primary" link class="info-btn">隐私条款</el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ElForm, ElMessage } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { UserFilled } from "@element-plus/icons-vue";
import { bizLoginPC, bizPhoneCode } from "@/biz/modules/user";
import { Eleme } from "@element-plus/icons-vue";
import { vaildPhoneNumber } from "@/utils/check";

const loading = ref(false);
const checked2 = ref(true);
// 登录表单数据
const loginForm = reactive({
  phone: "18246604221",
  code: "",
  clientId: "33f25d5380d6a9ff4c2abc782ca3c911",
  clientPassword: "C19152147AB60D08653B34864A1A7D11"
});
// 定义 formRef（校验规则）
type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  code: [{ required: true, message: "请输入短信验证码", trigger: "blur" }]
});

//按钮是否可点
const canClick = ref(true);
const totalTime = ref(60);
const buttonCtn = ref("发送短信验证码");

// 获取验证码
const getPhoneCode = () => {
  bizPhoneCode(loginForm.phone)
    .then(res => {
      if (res.data) {
        ElMessage.error("验证码已发送.");
      }
    })
    .catch(err => {
      console.log(err);
    });
};

//发送验证码
const handleSendCode = () => {
  if (!canClick.value) {
    return;
  }

  if (!loginForm.phone) {
    ElMessage.error("请输入接收验证码的手机号.");
    return;
  }

  if (!vaildPhoneNumber(loginForm.phone)) {
    ElMessage.error("请输入正确的手机号.");
    return;
  }

  //调用手机短信功能
  getPhoneCode();

  canClick.value = false;
  let clock = window.setInterval(() => {
    totalTime.value = totalTime.value - 1;
    buttonCtn.value = totalTime.value + " 秒后可重新发送";
    if (totalTime.value < 0) {
      window.clearInterval(clock);
      buttonCtn.value = " 重新发送验证码";
      totalTime.value = 60;
      canClick.value = true;
    }
  }, 1000);
};

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      bizLoginPC({ ...loginForm });
    } finally {
      loading.value = false;
    }
  });
};

onMounted(() => {
  // 监听enter事件（调用登录）
  document.onkeydown = (e: any) => {
    e = window.event || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});
</script>
<style scoped lang="scss">
.form-wrapper {
  position: relative;
  height: 320px;
  width: 100%;
}
.el-form-item {
  margin-bottom: 20px;
}
.login-btn {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-top: 40px;
  white-space: nowrap;
  .el-button {
    width: 100%;
  }
}

.captcha-frame-wrapper {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;

  .captcha-frame {
    width: 48%;
  }
  .captcha-box {
    width: 48%;
    height: 2.5rem;
    cursor: pointer;
    & img {
      width: 100%;
      height: 100%;
    }
  }
}

.info-wrapper {
  position: absolute;
  width: 100%;
  bottom: 20px;

  display: flex;
  align-items: center;
  justify-content: center;

  .note {
    color: var(--el-color-info);
    font-size: 12px;
    font-weight: 600;
  }

  .note-ml10 {
    margin-left: 10px;
  }

  .info-btn {
  }
}
</style>
